package com.ctshk.rpc.season.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.constant.RedisConstants;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.*;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.Assist;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.cms.service.IBannerPositionService;
import com.ctshk.rpc.cms.service.INoticePositionService;
import com.ctshk.rpc.season.dto.*;
import com.ctshk.rpc.season.entity.SeasonFixedProduct;
import com.ctshk.rpc.season.entity.SeasonFixedProductPackage;
import com.ctshk.rpc.season.entity.SeasonProductStrategyVaildDate;
import com.ctshk.rpc.season.entity.es.FixedSeasonDetails;
import com.ctshk.rpc.season.mapper.SeasonElasticSearchMapper;
import com.ctshk.rpc.season.mapper.SeasonFixedDepartDateMapper;
import com.ctshk.rpc.season.mapper.SeasonFixedProductMapper;
import com.ctshk.rpc.season.mapper.SeasonFixedProductPackageMapper;
import com.ctshk.rpc.season.req.*;
import com.ctshk.rpc.season.service.*;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.IMainDataTableService;
import com.ctshk.rpc.system.service.ISysPermissionService;
import com.ctshk.rpc.system.service.ISysUserService;
import com.ctshk.rpc.workflow.dto.ApprovalCheckDTO;
import com.ctshk.rpc.workflow.dto.ApprovalStartDTO;
import com.ctshk.rpc.workflow.service.ISysApprovalService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 套票-固定套票产品基本信息表 服务实现类
 * </p>
 *
 * @author 杨林
 * @since 2021-03-08
 */
@Slf4j
@DubboService
public class SeasonFixedProductServiceImpl extends ServiceImpl<SeasonFixedProductMapper, SeasonFixedProduct> implements ISeasonFixedProductService {

    @Autowired
    private SeasonFixedProductMapper seasonFixedProductMapper;
    @Autowired
    private SeasonFixedDepartDateMapper seasonFixedDepartDateMapper;
    @Autowired
    private SeasonFixedProductPackageMapper seasonFixedProductPackageMapper;
    @Autowired
    private ISeasonFixedProductPackageService seasonFixedProductPackageService;
    @Autowired
    private ISeasonFixedProductPackageTrainService seasonFixedProductPackageTrainService;
    @Autowired
    private ISeasonFixedProductPackageBusService seasonFixedProductPackageBusService;
    @Autowired
    private ISeasonFixedProductPackageAirService seasonFixedProductPackageAirService;
    @Autowired
    private ISeasonFixedProductPackageShipService seasonFixedProductPackageShipService;
    @Autowired
    private ISeasonFixedProductPackageScenicService seasonFixedProductPackageScenicService;
    @Autowired
    private ISeasonFixedProductPackageHotelService seasonFixedProductPackageHotelService;
    @Autowired
    private ISeasonFixedProductPackageLocalFunService seasonFixedProductPackageLocalFunService;
    @Autowired
    private ISeasonFixedProductPackageCommodityService seasonFixedProductPackageCommodityService;
    @Autowired
    private SeasonElasticSearchMapper seasonElasticSearchMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //审批服务类
    @DubboReference
    private ISysApprovalService sysApprovalService;
    @DubboReference
    private ISysPermissionService sysPermissionService;
    @DubboReference
    private ISysUserService iSysUserService;
    @DubboReference
    private IMainDataTableService iMainDataTableService;
    @DubboReference
    private INoticePositionService noticePositionService;
    @DubboReference
    private IBannerPositionService bannerPositionService;

    @Value("${cms.season.banner.id:1397033974181904385}")
    private Long cmsSeasonBannerId;

    @Value("${sys.season.main.fid:1376823817288216577}")
    private Long sysSeasonMainfid;

    @Value("${sys.season.main.tid:1376823777639460865}")
    private Long sysSeasonMainTid;

    @Value("${cms.season.notice.id:1397032375128670209}")
    private Long cmsSeasonNoticeId;


    @Value("${season.downloadPagaSize:100}")
    private int downloadPagaSize;

    /* @MethodName: 保存固定套表进本信息
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/8 16:03
     **/
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Result addSeasonFixedProduct(TokenUser user, SeasonFixedBaseReq req) {
        if (user == null) {
            return Result.failed(SystemError.USER_1000);
        }
        if (req == null) {
            return Result.failed(SystemError.SEASON_TICKET_20002);
        }
        String code = req.getCode();
        Long proId = req.getId();
        SeasonFixedProduct seasonFixedProduct = EntityUtil.copy(req, SeasonFixedProduct.class);
        if(proId==null || "".equals(proId)){
            log.info("添加套票-----===>");
            //检查固定套票 产品编码是否重复
            if (checkSeasonFixedProductCode(code) > 0) {
                return Result.failed(SystemError.SEASON_TICKET_20001);
            }
            //保存 固定套票信息
            LocalDateTime now = LocalDateTime.now();
            seasonFixedProduct.setCreateId(user.getId());
            seasonFixedProduct.setGmtCreate(now);
            seasonFixedProduct.setGmtModified(now);
            //因为正则那边需要验证需要String
            seasonFixedProduct.setTravelDays(Integer.parseInt(req.getTravelDays()));
            seasonFixedProduct.setTravelNights(Integer.parseInt(req.getTravelNights()));
            seasonFixedProduct.setMinPeopleNumber(Integer.parseInt(req.getMinPeopleNumber()));
            seasonFixedProduct.setIsDeleted(IsDeletedCode.NO.getCode());
            //审批状态（1 待提交，2 审批中，3 审批通过，4 审批不通过）
            seasonFixedProduct.setApprovalStatus(SeasonType.WAIT_SUBMIT.getCode());
            //售卖状态（ 1-有效  0-无效）当审批状态为通过时才会有售卖状态
            //mybatis 生成id
            long id = IdWorker.getId();
            seasonFixedProduct.setId(id);
            seasonFixedProductMapper.insert(seasonFixedProduct);
        }else{
            seasonFixedProduct.setId(proId);
            seasonFixedProductMapper.updateById(seasonFixedProduct);
        }
        return Result.success(seasonFixedProduct);
    }

    @Override
    public Result checkFixedSeasonProductCode(TokenUser user, String code) {
        if (user == null) {
            return Result.failed(SystemError.USER_1000);
        }
        if (StringUtils.isBlank(code)) {
            return Result.failed(SystemError.SEASON_TICKET_20003);
        }
        int count = checkSeasonFixedProductCode(code);
        if (count > 0) {
            return Result.failed(SystemError.SEASON_TICKET_20001);
        }
        return Result.success();

    }

    /* @MethodName: 保存固定套 补充信息
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/9 10:54
     **/
    @Override
    public Result addSeasonFixedProductReplenish(SeasonFixedReplenishReq seasonFixedReplenishReq) {
        //获取固定套票信息
        SeasonFixedProduct seasonFixedProduct = seasonFixedProductMapper.selectById(seasonFixedReplenishReq.getProductId());
        if (seasonFixedProduct == null) {
            return Result.failed(SystemError.SEASON_TICKET_20004);
        }
        seasonFixedProduct.setIncludesFee(seasonFixedReplenishReq.getIncludesFee());//费用包含
        seasonFixedProduct.setBookingInformation(seasonFixedReplenishReq.getBookingInformation());//预定须知
        seasonFixedProduct.setRemark(seasonFixedReplenishReq.getRemark());//备注
        seasonFixedProductMapper.updateById(seasonFixedProduct);
        return Result.success(seasonFixedProduct);
    }

    /* @MethodName: 获取固定套票详情信息
     * @Description: TODO
     * @Param: 用户 固定套餐id
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/10 17:08
     **/
    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public Result getFixedSeasonProductDetails(TokenUser user, Long productId) {
        if (user == null) {
            return Result.failed(SystemError.USER_1000);
        }
        Result result = getFixedSeasonProductDetails(productId);
        if (result.isSuccess()) {
            //固定套票各种产品设置
            FixedSeasonDetailsDTO detailsDTO = (FixedSeasonDetailsDTO) result.getData();
            seasonFixedProductPackageService.getProductSetInfo(detailsDTO);
            LocalDate now = LocalDate.now();
            LocalDate endDate = now.with(TemporalAdjusters.lastDayOfMonth());
            List<DepartCalendarDTO> departCalendarDTOList = getDepartCalendarDTOList(productId, now, endDate, detailsDTO, 1, user.getId());
            detailsDTO.setDepartCalendarDTOList(departCalendarDTOList);
            return Result.success(detailsDTO);
        } else {
            return result;
        }

    }

    /**
     * 查询详情信息
     * @param productId
     * @return
     */
    @Override
    public Result getFixedSeasonProductDetails(Long productId) {
        //固定套票
        if (productId == null || productId == 0l) {
            return Result.failed(SystemError.SEASON_TICKET_20005);
        }
        SeasonFixedProduct seasonFixedProduct = seasonFixedProductMapper.selectById(productId);
        if (seasonFixedProduct == null) {
            return Result.failed(SystemError.SEASON_TICKET_20004);
        }
        //根据固定套票id  获取该固定套票 打包信息
        SeasonFixedProductPackage seasonFixedProductPackage = getSeasonFixedProductPackage(productId);
        if (seasonFixedProductPackage == null) {
            return Result.failed(SystemError.SEASON_TICKET_20006);
        }
        FixedSeasonDetailsDTO detailsDTO = EntityUtil.copy(seasonFixedProduct, FixedSeasonDetailsDTO.class);
        List<String> themeList = new ArrayList<>();
        String theme = seasonFixedProduct.getTheme();
        if (StringUtils.isNotBlank(theme)) {//一般不会为空的
            if (theme.contains(",")) {//如果有多个主题
                String[] strList = theme.split(",");
                themeList = Arrays.asList(strList);
            } else {
                themeList.add(theme);
            }
        }
        detailsDTO.setThemeList(themeList);//产品主题id
        List<String> themeNameList = new ArrayList<>();//产品主题
        String themeName = seasonFixedProduct.getThemeName();
        if (StringUtils.isNotBlank(themeName)) {//一般不会为空的
            if (themeName.contains(",")) {//如果有多个主题
                String[] strList = themeName.split(",");
                themeNameList = Arrays.asList(strList);
            } else {
                themeNameList.add(themeName);
            }
        }
        detailsDTO.setThemeNameList(themeNameList);
        //固定套票产品设置信息
        copyPackage(detailsDTO, seasonFixedProductPackage);
        return Result.success(detailsDTO);
    }

    private void copyPackage(FixedSeasonDetailsDTO detailsDTO, SeasonFixedProductPackage seasonFixedProductPackage) {
        detailsDTO.setPackageId(seasonFixedProductPackage.getId());
        detailsDTO.setProductId(seasonFixedProductPackage.getProductId());
        detailsDTO.setPackageProductFlag(seasonFixedProductPackage.getPackageProductFlag());
        detailsDTO.setBackTerms(seasonFixedProductPackage.getBackTerms());
        detailsDTO.setSeasonTypeId(seasonFixedProductPackage.getSeasonTypeId());
        detailsDTO.setSeasonTypeName(seasonFixedProductPackage.getSeasonTypeName());
        detailsDTO.setTravelBrochureFile(seasonFixedProductPackage.getTravelBrochureFile());
    }

    /* @MethodName: 出发日期  结束 日期  来获取 资源中心 套票详情出行日历
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/4/2 16:10
     **/
    @Override
    public List<DepartCalendarDTO> getDepartCalendarDTOList(Long productId, LocalDate startDate, LocalDate endDate, FixedSeasonDetailsDTO detailsDTO, Integer channelType, Long relId) {
        List<DepartCalendarDTO> list = new LinkedList<>();
        //查询 可以出行的日期

        List<LocalDate> yesLocalDateList = seasonFixedDepartDateMapper.getYesDepartDate(productId, startDate, endDate);
        //List<SeasonProductStrategyVaildDate> strategyDateList = seasonFixedProductMapper.queryStrategDateyByProductId(productId, null, null);
        List<LocalDate> localDateList = new ArrayList<>();
        for (LocalDate date : yesLocalDateList) {
            //for (SeasonProductStrategyVaildDate strategyDate : strategyDateList) {
                //if (date.compareTo(strategyDate.getTimeBegin()) >= 0 && date.compareTo(strategyDate.getTimeEnd()) <= 0) {
                    localDateList.add(date);
                    //break;
                //}
            //}
        }
        List<LocalDate> sectionDateList = DateUtil.getSectionDate(startDate, endDate);
        for (LocalDate date : sectionDateList) {
            DepartCalendarDTO dto = new DepartCalendarDTO();
            dto.setDepartDate(date);
            BigDecimal fixedSeasonCostPrice = BigDecimal.ZERO;
            if (localDateList.contains(date)) {
                //获取固定套票 打包产品的 价格
                if (null != detailsDTO) {
                    seasonFixedProductPackageService.getPackageProduct(detailsDTO, date, detailsDTO.getTravelDays(), detailsDTO.getTravelNights(), SeasonType.OFFLINE_SELF_CHANNEL_TYPE.getCode(),detailsDTO.getChargeUserId());
                    BigDecimal cost = seasonFixedProductPackageService.getFixedSeasonProductCosts(detailsDTO);
                    //获取固定套票加幅值
                    fixedSeasonCostPrice = seasonFixedProductPackageService.getFixedSeasonAdjust(cost, relId, date, productId, channelType);
                }
                dto.setIfShow(1);

            } else {
                dto.setIfShow(0);
            }
            dto.setCost(fixedSeasonCostPrice);
            list.add(dto);
        }
        if (list.size() > 0) {
            list.get(0).setValidDateList(localDateList);
            list.get(0).setDepartDateList(yesLocalDateList);
        }
        return list;
    }


    /* @MethodName: 查询 使用推广码的产品
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/4/21 18:27
     **/
    @Override
    public PageResponse<FixedSeasonProductPageDTO> getEmployCouponCodeSeason(SearchFixedProductReq req, TokenUser user) {
        req.setSellStatus(SeasonType.VALID.getCode());
        req.setApprovalStatus(SeasonType.REVIEW_PASS.getCode());
        return getSeasonFixedProduct(req);
    }

    /* @MethodName: 根据ids 获取固定套票信息
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/4/22 16:15
     **/
    @Override
    public List<FixedSeasonProductPageDTO> getSeasonProductList(String ids) {
        List<FixedSeasonProductPageDTO> resultList = seasonFixedProductMapper.getSeasonProductList(ids);
        return resultList;
    }

    @Override
    public Result<HomePageAppDTO> onLineSeasonHomePage(Long userId, AppSearchFixedProductReq req) {

        //先查一遍redis
        String cacheStr = redisTemplate.opsForValue().get(RedisConstants.FIX_PRODUCT_HOME_PAGE_CACHE);

        if(org.apache.commons.lang.StringUtils.isBlank(cacheStr)){
            //没有缓存

            log.info("没有命中缓存，开始查询数据");

            SearchFixedProductReq newreq = EntityUtil.copy(req, SearchFixedProductReq.class);
            HomePageAppDTO homePageAppDTO = new HomePageAppDTO();
            newreq.setChannelId(SeasonType.ONLINE_SELF_CHANNEL_TYPE.getCode());
            newreq.setRelId(req.getChannelId());
            newreq.setCachePrice(true);
            //Banner列表
            //  Result<BannerPositionListDTO> cmsSeasonBanner = bannerPositionService.getBannerPositionById(cmsSeasonBannerId);
            // homePageAppDTO.setBanners(EntityUtil.copyList(cmsSeasonBanner.getData().getBanners(), BannerDTO.class));
            //类型列表
//        List<MainDataRowFieldDataDTO> sysSeasonMain = iMainDataTableService.groupByDataField(sysSeasonMainTid, sysSeasonMainfid);
//        homePageAppDTO.setSysSeasonMain(EntityUtil.copyList(sysSeasonMain, com.ctshk.rpc.season.dto.MainDataRowFieldDataDTO.class));


//            List<MainDataRowFieldDataDTO> sysSeasonMain = new ArrayList<>();
//            MainDataRowFieldDataDTO sysMain = new MainDataRowFieldDataDTO();
//            sysMain.setId(1L);
//            sysMain.setFieldValue("火车+酒店");
//            sysSeasonMain.add(sysMain);
//            sysMain = new MainDataRowFieldDataDTO();
//            sysMain.setId(2L);
//            sysMain.setFieldValue("机票+酒店");
//            homePageAppDTO.setSysSeasonMain(sysSeasonMain);
            //热门列表
//            List<HotCityDataDTO> hotCity = new ArrayList<>();
//            // req.setArrCityId(SeasonOrderManager.AREA_HK);
//            PageResponse<AppFixedSeasonProductDTO> seasonFixedsHK = getAppSeasonFixedProduct(newreq);
//            hotCity.add(new HotCityDataDTO(1L, "香港", seasonFixedsHK.getRecords()));
//            //req.setArrCityId(SeasonOrderManager.AREA_MO);
//            PageResponse<AppFixedSeasonProductDTO> seasonFixedsMO = getAppSeasonFixedProduct(newreq);
//            hotCity.add(new HotCityDataDTO(2L, "澳门", seasonFixedsMO.getRecords()));
//            homePageAppDTO.setHotCity(hotCity);


            //公告列表
//        Result<NoticePositionListDTO> cmsSeasonNotice = noticePositionService.getNoticePositionById(cmsSeasonNoticeId);
//        homePageAppDTO.setNoticeDTOS(EntityUtil.copyList(cmsSeasonNotice.getData().getNoticeDTOS(), NoticeDTO.class));
            //搜索列表
            // newreq.setIsRecommend(SeasonType.IS_RECOMMEND.getCode());
            newreq.setArrCityId(null);
            PageResponse<AppFixedSeasonProductDTO> seasonFixeds = getAppSeasonFixedProduct(newreq);

            for(AppFixedSeasonProductDTO appFixedSeasonProductDTO :seasonFixeds.getRecords()){
                if(appFixedSeasonProductDTO.getCachePrice() != null){
                    appFixedSeasonProductDTO.setProductPrice(appFixedSeasonProductDTO.getCachePrice());
                }
            }

            homePageAppDTO.setSeasonFixeds(seasonFixeds.getRecords());

            if(!seasonFixeds.getRecords().isEmpty()){
                redisTemplate.opsForValue().set(RedisConstants.FIX_PRODUCT_HOME_PAGE_CACHE,JSONObject.toJSONString(homePageAppDTO),1, TimeUnit.DAYS);
            }



            return Result.success(homePageAppDTO);
        }

        log.info("命中了缓存，返回缓存数据");

        HomePageAppDTO homePageAppDTO = JSONObject.parseObject(cacheStr, HomePageAppDTO.class);

        return Result.success(homePageAppDTO);
    }

    @Override
    public Result<PageResponse<AppFixedSeasonProductDTO>> onLineSeasonSearch(Long userId, AppSearchFixedProductReq req) {
        SearchFixedProductReq newreq = EntityUtil.copy(req, SearchFixedProductReq.class);
        newreq.setChannelId(SeasonType.ONLINE_SELF_CHANNEL_TYPE.getCode());
        newreq.setRelId(req.getChannelId());
        return Result.success(getAppSeasonFixedProduct(newreq));
    }

    @Override
    public FixedSeasonProductCertificatesDTO getPackageProductByProductId(Long productId) {
        return seasonFixedProductMapper.getPackageProductByProductId(productId);
    }

    @Override
    public Result searchInit(SearchFixedProductReq req) {
        // 删除es旧缓存数据
        LocalDateTime now = LocalDateTime.now();
        // 检索缓存上架es
        if (req != null) {
            req.setPageNo(1);
            req.setPageSize(downloadPagaSize);
//            productWrapper.ge(req.getStartTime() != null, LocalFunProduct::getGmtModified, req.getStartTime());
//            productWrapper.le(req.getEndTime() != null, LocalFunProduct::getGmtModified, req.getEndTime());
//            productWrapper.in(req.getIds() != null, LocalFunProduct::getId, req.getIds());
        }

        IPage<FixedSeasonProductPageDTO> seasonPages = new Page<>(req.getPageNo(), req.getPageSize());
        //搜索固定套票列表 处理第一页的数据
        handlerPagas(req);
        long total = seasonPages.getTotal();
        int totalPagas = 0;
        totalPagas = (int) total / req.getPageSize() + 1;
        //分页缓存
        for (int i = 2; i <= totalPagas; i++) {
            req.setPageNo(i);
            handlerPagas(req);
        }
        // 标记缓存更新时间
        setUpdateTime(RedisConstants.SEASON_UPDATE_TIME, now);
        return Result.success();
    }

    @Override
    public Result upElasticSearch(List<FixedSeasonDetailsDTO> seasonProductCacheUpDTOS) {
        seasonElasticSearchMapper.deleteAll();
        List<FixedSeasonDetails> fixedSeasonDetails = EntityUtil.copyList(seasonProductCacheUpDTOS, FixedSeasonDetails.class);
        seasonElasticSearchMapper.saveAll(fixedSeasonDetails);
        return Result.success();
    }


    private List<FixedSeasonDetailsDTO> handlerPagas(SearchFixedProductReq req) {
        List<FixedSeasonDetailsDTO> seasonProductCacheUpDTOS = builProductData(req);
        upElasticSearch(seasonProductCacheUpDTOS);
        upRedis(seasonProductCacheUpDTOS);
        return seasonProductCacheUpDTOS;
    }

    /**
     * 固定套票 - 构建产品缓存数据
     */
    private List<FixedSeasonDetailsDTO> builProductData(SearchFixedProductReq req) {
        LocalDate startDate = LocalDate.now();
        //添加各个单项的值
        LocalDate endDate = startDate.plusMonths(1).with(TemporalAdjusters.lastDayOfMonth());
        IPage<FixedSeasonProductPageDTO> seasonPages = new Page<>(req.getPageNo(), req.getPageSize());
        //搜索固定套票列表
        seasonPages = seasonFixedProductMapper.searchSeasonFixedProduct(req, seasonPages);
        List<FixedSeasonDetailsDTO> seasonProductCacheUpDTOS = new ArrayList<>();
        if (null != seasonPages && null != seasonPages.getRecords() && seasonPages.getRecords().size() > 0) {
            Map<Long, String> chargeUserNameMap = new HashMap<>();
            seasonPages.getRecords().forEach(item -> {
                FixedSeasonDetailsDTO fixedSeasonDetailsDTO = EntityUtil.copy(item, FixedSeasonDetailsDTO.class);
                if (chargeUserNameMap.containsKey(item.getChargeUserId())) {
                    fixedSeasonDetailsDTO.setChargeUserName(chargeUserNameMap.get(item.getChargeUserId()));
                } else {
                    UserDTO userDTO = iSysUserService.queryCacheUser(item.getChargeUserId());
                    String createDept = userDTO.getCreateDept();
                    chargeUserNameMap.put(item.getChargeUserId(), createDept);
                    fixedSeasonDetailsDTO.setChargeUserName(createDept);
                }
                List<DepartCalendarDTO> departCalendarDTOList = getDepartCalendarDTOList(item.getProductId(), startDate, endDate, fixedSeasonDetailsDTO, SeasonType.ONLINE_SELF_CHANNEL_TYPE.getCode(), null);
                fixedSeasonDetailsDTO.setDepartCalendarDTOList(departCalendarDTOList);
                if (null != departCalendarDTOList && departCalendarDTOList.size() > 0) {
                    //获取固定套票 打包产品的 价格
                    LocalDate departDate = departCalendarDTOList.get(0).getValidDateList().get(0);
                    seasonFixedProductPackageService.getPackageProduct(fixedSeasonDetailsDTO, departDate, fixedSeasonDetailsDTO.getTravelDays(), fixedSeasonDetailsDTO.getTravelNights(), 3,req.getRelId());
                    //获取固定套票加幅值
                    BigDecimal cost = seasonFixedProductPackageService.getFixedSeasonProductCosts(fixedSeasonDetailsDTO);
                    BigDecimal fixedSeasonCostPrice = seasonFixedProductPackageService.getFixedSeasonAdjust(cost, req.getChargeUserId(), departDate, item.getProductId(), 3);
                    fixedSeasonDetailsDTO.setProductPrice(fixedSeasonCostPrice);
                }
                seasonProductCacheUpDTOS.add(fixedSeasonDetailsDTO);
            });
        }
        return seasonProductCacheUpDTOS;
    }


    /**
     * 设置缓存 上架/更新 时间
     *
     * @param key
     */
    private void setUpdateTime(String key, LocalDateTime now) {
        redisTemplate.opsForValue().set(key, now.toString());
    }


    /**
     * 产品详情上架redis
     *
     * @param seasonProductCacheUpDTOS
     * @return
     */
    private Result upRedis(List<FixedSeasonDetailsDTO> seasonProductCacheUpDTOS) {
        // 封装缓存上架数据
        Map<String, String> map = new HashMap<>();
        Assist.forEach(seasonProductCacheUpDTOS, item -> {
            map.put(item.getId().toString(), item.toString());
        });
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(RedisConstants.SEASON_PRODUCT_DETAILS);
        hashOps.putAll(map);
        return Result.success();
    }


    /**
     * 搜索 固定套票
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public PageResponse<FixedSeasonProductPageDTO> searchSeasonFixedProduct(SearchFixedProductReq req, TokenUser user) {
        if (!GlobalConstants.Role.isAdmin(user.getUsername())) {
            if (req.getMenuId() == null) {
                throw new BusinessException(SystemError.SYSTEM_2106);
            }
            Result<List<Long>> permissionResult = sysPermissionService.queryPermission(req.getMenuId(), user.getId());
            if (!permissionResult.isSuccess()) {
                SystemError result = SystemError.getDefined(permissionResult.getCode());
                throw new BusinessException(result);
            }
            req.setChargeUserIds(permissionResult.getData());
            req.setUserId(user.getId());
        }
        return getSeasonFixedProduct(req);
    }


    private PageResponse<FixedSeasonProductPageDTO> getSeasonFixedProduct(SearchFixedProductReq req) {
        req.setOnline(false);
        IPage<FixedSeasonProductPageDTO> page = new Page<>(req.getPageNo(), req.getPageSize());
        //搜索固定套票列表
        page = seasonFixedProductMapper.searchSeasonFixedProduct(req, page);
        if (null != page && null != page.getRecords() && page.getRecords().size() > 0) {
            Map<Long, String> chargeUserNameMap = new HashMap<>();
            page.getRecords().forEach(records -> {
                if (chargeUserNameMap.containsKey(records.getChargeUserId())) {
                    records.setChargeUserName(chargeUserNameMap.get(records.getChargeUserId()));
                } else {
                    UserDTO userDTO = iSysUserService.getByUserId(records.getChargeUserId());
                    if(null != userDTO) {
                        String createDept = userDTO.getCreateDept();
                        chargeUserNameMap.put(records.getChargeUserId(), createDept);
                        records.setChargeUserName(createDept);
                    }
                }
            });
        }
        PageResponse<FixedSeasonProductPageDTO> result = new PageResponse<>(page.getRecords(), page.getCurrent() == 1,
                page.getTotal() <= (page.getCurrent() * page.getSize()), page.getTotal(), page.getCurrent(), page.getSize());
        return result;
    }


    /**
     * 查询固定套票产品
     * @param req
     * @return
     */
    private PageResponse<AppFixedSeasonProductDTO> getAppSeasonFixedProduct(SearchFixedProductReq req) {
        IPage<FixedSeasonProductPageDTO> page = new Page<>(req.getPageNo(), req.getPageSize());
        //搜索固定套票列表
        page = seasonFixedProductMapper.searchSeasonFixedProduct(req, page);
        List<AppFixedSeasonProductDTO> appFSeasonProDTOs = new ArrayList<>();
        if (null != page && null != page.getRecords() && page.getRecords().size() > 0) {
            page.getRecords().forEach(records -> {
                AppFixedSeasonProductDTO appFixedSeasonProductDTO = EntityUtil.copy(records, AppFixedSeasonProductDTO.class);
                List<IntroducePictureDTO> introducePictures = JSONArray.parseArray(records.getIntroducePicture(), IntroducePictureDTO.class);
                if (null != introducePictures && introducePictures.size() > 0) {
                    appFixedSeasonProductDTO.setIntroducePicture(introducePictures.get(0).getUrl());
                }
                LocalDate departDate = LocalDate.now();
                //默认产品的价格
                PackageProductCostDTO packageProductCostDTO = getPackageProduct(records.getPackageProductFlag(), records.getPackageId(), departDate, records.getTravelDays(), records.getTravelNights(), appFixedSeasonProductDTO.getChargeUserId(), SeasonType.OFFLINE_SELF_CHANNEL_TYPE.getCode());
                log.info("套票产品默认价格为："+packageProductCostDTO.getCostPrice());

                //加幅价格
                BigDecimal fixedSeasonCostPrice = seasonFixedProductPackageService.getFixedSeasonAdjust(packageProductCostDTO.getCostPrice(), req.getRelId(), departDate, records.getProductId(), req.getChannelId());
                log.info("套票产品加幅后的价格为："+fixedSeasonCostPrice);

                //只判断套票产品的默认价格大于零，不包含加幅价格
                if(packageProductCostDTO.getCostPrice().compareTo(BigDecimal.ZERO) > 0){
                    // 更新数据的缓存要带上加幅价格
                    seasonFixedProductMapper.updateCachePrice(appFixedSeasonProductDTO.getProductId(),fixedSeasonCostPrice);
                }

                appFixedSeasonProductDTO.setProductPrice(fixedSeasonCostPrice);
                appFSeasonProDTOs.add(appFixedSeasonProductDTO);
            });
        }
        PageResponse<AppFixedSeasonProductDTO> result = new PageResponse<>(appFSeasonProDTOs, page.getCurrent() == 1,
                page.getTotal() <= (page.getCurrent() * page.getSize()), page.getTotal(), page.getCurrent(), page.getSize());
        return result;
    }

    /* @MethodName: 操作固定套票
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/12 11:43IAirProductAppService.
     **/
//    @Override
//    public Result updateFixedSeasonProductState(TokenUser user, SeasonFixedProductStateReq req) {
//        Result result = null;
//        SeasonFixedProduct seasonFixedProduct = seasonFixedProductMapper.selectById(req.getProductId());
//        if (seasonFixedProduct == null) {
//            return Result.failed(SystemError.SEASON_TICKET_20004);
//        }
//        if (user == null) {
//            return Result.failed(SystemError.USER_1000);
//        }
//        String operationType = req.getOperationType();//操作类型  1:提交审批   2:设置有效 无效
//        if (SeasonType.VALID.getKey().equals(operationType)) {//提交审批
//            if (SeasonType.REVIEW_PASS.getCode() == seasonFixedProduct.getApprovalStatus()) {
//                seasonFixedProduct.setSellStatus(SeasonType.VALID.getCode());
//            } else {
//                //更改审批状态
//                seasonFixedProduct.setApprovalStatus(SeasonType.APPROVAL.getCode());//审批中
//                //固定套票业务类型枚举
//                long businessTypeId = SystemBusinessType.FIXED_PACKAGE_TICKET.getCode();
//                //审批类型id
//                long approvalTypeId = SysApprovalType.ADD_FIXED.getCode();
//                long businessId = seasonFixedProduct.getId();
//                long userId = user.getId();
//                //添加一个审批流程
//                result = sysApprovalService.start(businessTypeId, approvalTypeId, businessId, userId, null, null);
//            }
//        } else if (SeasonType.INVALID.getKey().equals(operationType)) {//设置无效
//            seasonFixedProduct.setSellStatus(SeasonType.INVALID.getCode());
//        }
//        seasonFixedProductMapper.updateById(seasonFixedProduct);
//        if (null == result) {
//            result = Result.success();
//        }
//        return result;
//    }
    @Override
    public Result updateFixedSeasonProductState(TokenUser user, SeasonFixedProductStateReq req) {
        Result result = null;
        if (user == null) {
            return Result.failed(SystemError.USER_1000);
        }
        String operationType = req.getOperationType();//操作类型  1:提交审批   2:设置有效 无效
        String[] split = req.getProductId().split(",");
        if(split.length==1){
            SeasonFixedProduct seasonFixedProduct = seasonFixedProductMapper.selectById(req.getProductId());
            if (seasonFixedProduct == null) {
                return Result.failed(SystemError.SEASON_TICKET_20004);
            }
            if (SeasonType.VALID.getKey().equals(operationType)) {//提交审批
                if (SeasonType.REVIEW_PASS.getCode() == seasonFixedProduct.getApprovalStatus()) {
                    seasonFixedProduct.setSellStatus(SeasonType.VALID.getCode());
                } else {
                    //更改审批状态
                    seasonFixedProduct.setApprovalStatus(SeasonType.APPROVAL.getCode());//审批中
                    //固定套票业务类型枚举
                    long businessTypeId = SystemBusinessType.FIXED_PACKAGE_TICKET.getCode();
                    //审批类型id
                    long approvalTypeId = SysApprovalType.ADD_FIXED.getCode();
                    long businessId = seasonFixedProduct.getId();
                    long userId = user.getId();
                    //添加一个审批流程
                    result = sysApprovalService.start(businessTypeId, approvalTypeId, businessId, userId, null, null);
                }
            } else if (SeasonType.INVALID.getKey().equals(operationType)) {//设置无效
                seasonFixedProduct.setSellStatus(SeasonType.INVALID.getCode());
            }
            seasonFixedProductMapper.updateById(seasonFixedProduct);
            if (null == result) {
                result = Result.success();
            }
            return result;
        }else{
            Result<List<ApprovalStartDTO>> result2 = new Result<>();
            List<ApprovalStartDTO> list = new ArrayList<>();
            List<SeasonFixedProduct> seasonFixedProducts = seasonFixedProductMapper.selectBatchIds(Arrays.asList(split));
            if(null == seasonFixedProducts || seasonFixedProducts.size()==0){
                return Result.failed(SystemError.SEASON_TICKET_20004);
            }
            seasonFixedProducts.forEach(seasonFixedProduct->{
                Result<ApprovalStartDTO> res = null;
                if (SeasonType.VALID.getKey().equals(operationType)) {
                    if (SeasonType.REVIEW_PASS.getCode() == seasonFixedProduct.getApprovalStatus()) {
                        seasonFixedProduct.setSellStatus(SeasonType.VALID.getCode());
                    } else {
                        seasonFixedProduct.setApprovalStatus(SeasonType.APPROVAL.getCode());//审批中
                        //固定套票业务类型枚举
                        long businessTypeId = SystemBusinessType.FIXED_PACKAGE_TICKET.getCode();
                        //审批类型id
                        long approvalTypeId = SysApprovalType.ADD_FIXED.getCode();
                        long businessId = seasonFixedProduct.getId();
                        long userId = user.getId();
                        //添加一个审批流程
                        res = sysApprovalService.start(businessTypeId, approvalTypeId, businessId, userId, null, null);
                        ApprovalStartDTO data = res.getData();
                        list.add(data);
                    }
                }else if (SeasonType.INVALID.getKey().equals(operationType)) {//设置无效
                    seasonFixedProduct.setSellStatus(SeasonType.INVALID.getCode());
                }
            });
            this.updateBatchById(seasonFixedProducts);
            result2.setData(list);
            if (result2.getData().size()==0) {
                result2 = (Result<List<ApprovalStartDTO>>) Result.success();
            }
            return result2;
        }
    }


    /* @MethodName: 编辑固定套票信息
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/12 15:20
     **/
    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public Result updateFixedSeason(TokenUser user, SeasonFixedReq req) {
        if (user == null) {
            return Result.failed(SystemError.USER_1000);
        }
        //获取固定套票信息 如果没有直接返回错误
        SeasonFixedProduct seasonFixedProduct = seasonFixedProductMapper.selectById(req.getProductId());
        if (seasonFixedProduct == null) {
            return Result.failed(SystemError.SEASON_TICKET_20004);
        }
        // 產品編號、不能更改
        // seasonFixedProduct.setCode(req.getCode());
        seasonFixedProduct.setProductName(req.getProductName());
        seasonFixedProduct.setSeasonTypeId(req.getSeasonTypeId().toString());
        seasonFixedProduct.setSeasonTypeName(req.getSeasonTypeName());
        //、旅遊組別碼、出發地、目的地、
        // seasonFixedProduct.setDepCityId(req.getDepCityId());
        //seasonFixedProduct.setDepCityName(req.getDepCityName());
        // seasonFixedProduct.setArrCityId(req.getArrCityId());
        //seasonFixedProduct.setArrCityName(req.getArrCityName());

        seasonFixedProduct.setSubtitle(req.getSubtitle());
        // 產品編號、負責人員 不能更改
        //seasonFixedProduct.setChargeUserId(req.getChargeUserId());
        // seasonFixedProduct.setChargeUserName(req.getChargeUserName());

        // 、旅遊組別碼
        // seasonFixedProduct.setTravelGroup(req.getTravelGroup());
        // seasonFixedProduct.setTravelGroupId(req.getTravelGroupId());
        seasonFixedProduct.setKind(req.getKind());
        //行程天數
        // seasonFixedProduct.setTravelDays(Integer.parseInt(req.getTravelDays()));
        //seasonFixedProduct.setTravelNights(Integer.parseInt(req.getTravelNights()));

        seasonFixedProduct.setMinPeopleNumber(Integer.parseInt(req.getMinPeopleNumber()));
        seasonFixedProduct.setFeature(req.getFeature());
        seasonFixedProduct.setApplicableCrowdId(req.getApplicableCrowdId());
        seasonFixedProduct.setApplicableCrowdName(req.getApplicableCrowdName());
        seasonFixedProduct.setTheme(req.getTheme());

        seasonFixedProduct.setThemeName(req.getThemeName());
        seasonFixedProduct.setIntroducePicture(req.getIntroducePicture());
        seasonFixedProduct.setIntroduceVideo(req.getIntroduceVideo());
        seasonFixedProduct.setIntroduce(req.getIntroduce());
        seasonFixedProduct.setIncludesFee(req.getIncludesFee());

        seasonFixedProduct.setBookingInformation(req.getBookingInformation());
        seasonFixedProduct.setRemark(req.getRemark());
        seasonFixedProduct.setIncludesFee(req.getIncludesFee());
        seasonFixedProduct.setIncludesFee(req.getIncludesFee());
        seasonFixedProduct.setIncludesFee(req.getIncludesFee());
        seasonFixedProduct.setModifiedId(user.getId());//修改人
        LocalDateTime now = LocalDateTime.now();
        seasonFixedProduct.setGmtModified(now);//修改时间
        //重新编辑后 需要将审核状态改为待提交
        seasonFixedProduct.setApprovalStatus(SeasonType.WAIT_SUBMIT.getCode());
        //售卖状状态 在编辑的时候 也要改
        seasonFixedProduct.setSellStatus(SeasonType.INVALID.getCode());
        seasonFixedProductMapper.updateById(seasonFixedProduct);
        //根据固定套票id  获取该固定套票 打包信息
        Long packageId = req.getPackageId();
        SeasonFixedProductPackage seasonFixedProductPackage = seasonFixedProductPackageMapper.selectById(packageId);
        if (seasonFixedProductPackage == null) {
            return Result.failed(SystemError.SEASON_TICKET_20006);
        }
        seasonFixedProductPackage.setPackageProductFlag(req.getPackageProductFlag());
        seasonFixedProductPackage.setBackTerms(req.getBackTerms());
        seasonFixedProductPackage.setSeasonTypeId(req.getSeasonTypeId());
        seasonFixedProductPackage.setSeasonTypeName(req.getSeasonTypeName());
        seasonFixedProductPackage.setTravelBrochureFile(req.getTravelBrochureFile());
        seasonFixedProductPackage.setModifiedId(user.getId());//修改人
        seasonFixedProductPackage.setGmtModified(now);//修改时间

        seasonFixedProductPackageMapper.updateById(seasonFixedProductPackage);
        //批量处理套票相关产品信息
        seasonFixedProductPackageService.batchUpdateProductInfo(user, req, true, packageId);
        return Result.success();
    }


    /* @MethodName: 上架或者下架 固定套票产品
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/16 11:15
     **/
    @Override
    public void onShelfProduct(Long productId, int stateCode) {
        //seasonFixedProductMapper.getClass()
        UpdateWrapper<SeasonFixedProduct> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("on_shelf_status", stateCode);
        updateWrapper.eq("id", productId);
        seasonFixedProductMapper.update(null, updateWrapper);
    }


    /* @MethodName: 获取固定套票的 打包的 产品的价格
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/20 11:20
     **/
    @Override
    public PackageProductCostDTO getPackageProduct(String seasonPackageProductFlag
            , Long packageId, LocalDate queryDate, Integer travelDays, Integer travelNights, Long userId, Integer channelType) {
        BigDecimal big = BigDecimal.ZERO;
        boolean flag = false;
        String str[] = seasonPackageProductFlag.split(",");
        for (String productFlag : str) {
            BigDecimal singlePrice = getSinglePrice(productFlag, packageId, queryDate, travelDays, travelNights, userId, channelType);
            if (singlePrice.compareTo(BigDecimal.ZERO) != 0) {
                flag = true;
            }

            //add 方法不会改变子身的值 需要一个值去接收结果
            big = big.add(singlePrice);
        }
        PackageProductCostDTO productCostDTO = new PackageProductCostDTO();
        productCostDTO.setCostPrice(big);
        productCostDTO.setIsShow(flag);
        return productCostDTO;
    }


    /* @MethodName: 获取单项的价格
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/4/19 15:26
     **/
    private BigDecimal getSinglePrice(String productFlag, Long packageId, LocalDate queryDate, Integer travelDays, Integer travelNights, Long userId, Integer channelType) {
        //套票的选择的产品 1:机票 2:酒店 3:巴士 4:船票 5:火车票 6:景点门票 7:当地玩乐
        SeasonIndividualType productFlagEnum = SeasonIndividualType.getEnumType(productFlag);
        switch (productFlagEnum) {
            //机票
            case AIR:
                BigDecimal airCost = seasonFixedProductPackageAirService.getDefaultAirPrice(packageId, queryDate, DateUtil.getNextNDay(queryDate, travelDays), userId, channelType);
                return airCost;
            //酒店+
            case HOTEL:
                BigDecimal hotelCost = seasonFixedProductPackageHotelService.getDefaultHotelPrice(packageId, queryDate, DateUtil.getNextNDay(queryDate, travelNights), userId, channelType);

                log.info("酒店返回的金额为："+hotelCost);

                return hotelCost;
            //巴士
            case BUS:
                BigDecimal busCost = seasonFixedProductPackageBusService.getDefaultBusPrice(packageId, queryDate, DateUtil.getNextNDay(queryDate, travelDays), userId, channelType);
                return busCost;
            //船票
            case SHIP:
                BigDecimal shipCost = seasonFixedProductPackageShipService.getDefaultShipPrice(packageId, queryDate, DateUtil.getNextNDay(queryDate, travelDays), userId, channelType);
                return shipCost;
            //火车
            case TRAIN:
                BigDecimal trainCost = seasonFixedProductPackageTrainService.getDefaultTrainPrice(packageId, queryDate, DateUtil.getNextNDay(queryDate, travelDays), userId, channelType);
                return trainCost;
            //景点门票
            case SCENIC:
                BigDecimal scenicCost = seasonFixedProductPackageScenicService.getDefaultScenicPrice(packageId, queryDate, userId, channelType);
                return scenicCost;
            //当地玩乐
            case LOCALFUN:
                BigDecimal localFunCost = seasonFixedProductPackageLocalFunService.getDefaultLocalFunPrice(packageId, queryDate, userId, channelType);

                log.info("当地玩乐返回的金额为："+localFunCost);

                return localFunCost;
            //商品
            case COMMODITY:
                BigDecimal commodityCost = seasonFixedProductPackageCommodityService.getDefaultCommodityPrice(packageId, queryDate, userId, channelType);
                return commodityCost;
            default:
                return BigDecimal.ZERO;
        }

    }

    @Override
    public FixedSeasonDetailsDTO getFixedProductBaseDTO(Long productId) {
        SeasonFixedProduct seasonFixedProduct = seasonFixedProductMapper.selectOne(
                new QueryWrapper<SeasonFixedProduct>().lambda()
                        .eq(SeasonFixedProduct::getId, productId)
                        .eq(SeasonFixedProduct::getIsDeleted, IsDeletedCode.NO.getCode())
        );
        if (null != seasonFixedProduct) {
            FixedSeasonDetailsDTO baseDTO = EntityUtil.copy(seasonFixedProduct, FixedSeasonDetailsDTO.class);
            SeasonFixedProductPackage productPackage = seasonFixedProductPackageMapper.selectOne(
                    new QueryWrapper<SeasonFixedProductPackage>().lambda()
                            .eq(SeasonFixedProductPackage::getProductId, productId)
                            .eq(SeasonFixedProductPackage::getIsDeleted, IsDeletedCode.NO.getCode())
            );
            if (null != productPackage) {
                copyPackage(baseDTO, productPackage);
            }
            return baseDTO;
        } else {
            return null;
        }
    }

    /* @MethodName: 固定套票 流程审核
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/4/2 14:46
     **/
    @Override
    public Result flowCheckFixedSeason(TokenUser user, FlowCheckFixedSeasonReq req) {
        SeasonFixedProduct seasonFixedProduct = seasonFixedProductMapper.selectById(req.getBusinessId());
        if (null == seasonFixedProduct) {
            return Result.failed(SystemError.SEASON_TICKET_20004);
        }
        Integer status = req.getStatus();
        String comments = req.getComments();
        Result<ApprovalCheckDTO> result = sysApprovalService.check(req.getApprovalId(), req.getUserId(), status, comments);
        if (result.isSuccess()) {//标识成功
            ApprovalCheckDTO checkDTO = result.getData();
            boolean isFinish = checkDTO.getIsFinish();
            if (isFinish) {//审核完成
                //审批不通过
                if (SeasonType.APPROVAL_FAIL.getCode() == status) {
                    seasonFixedProduct.setApprovalStatus(SeasonType.APPROVAL_FAIL.getCode());
                    seasonFixedProduct.setSellStatus(SeasonType.INVALID.getCode());
                }
                //审批通过
                if (SeasonType.REVIEW_PASS.getCode() == status) {
                    seasonFixedProduct.setApprovalStatus(SeasonType.REVIEW_PASS.getCode());
                    seasonFixedProduct.setSellStatus(SeasonType.VALID.getCode());
                }
                seasonFixedProduct.setGmtModified(LocalDateTime.now());
                seasonFixedProduct.setModifiedId(user.getId());
                seasonFixedProduct.setComments(comments);
                seasonFixedProductMapper.updateById(seasonFixedProduct);
            }
        }
        return result;
    }


    /* @MethodName: 根据固定套票编号 检查是否重复 1:已有(重复)  0：没有 删除的编号 还可以用
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/8 16:15
     **/
    public int checkSeasonFixedProductCode(String code) {
        QueryWrapper<SeasonFixedProduct> qw = new QueryWrapper<>();
        qw.eq("code", code);
        qw.eq("is_deleted", 0);//没有删除
        qw.last("limit 1");
        return seasonFixedProductMapper.selectCount(qw);

    }


    /* @MethodName: 根据固定套票id 获取固定套票打包信息
     * @Description: TODO
     * @Param: 固定套票id
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/11 10:47
     **/

    public SeasonFixedProductPackage getSeasonFixedProductPackage(Long fixedSeasonId) {
        QueryWrapper<SeasonFixedProductPackage> qw = new QueryWrapper<>();
        qw.eq("product_id", fixedSeasonId);
        qw.eq("is_deleted", 0);//没有删除
        qw.last("limit 1");
        return seasonFixedProductPackageMapper.selectOne(qw);
    }

}
